package com.zaozhuang.robot;

import static com.zaozhuang.robot.SettingsActivity.KEY_WAKE_WORD;
import static com.zaozhuang.robot.SettingsActivity.KEY_WELCOME_MSG;
import static com.zaozhuang.robot.SettingsActivity.PREFS_NAME;
import static com.zaozhuang.robot.SettingsActivity.wake_default;
import static com.zaozhuang.robot.SettingsActivity.welcome_default;

import android.Manifest;
import android.animation.ValueAnimator;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.icu.text.Transliterator;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.RemoteException;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.helang.lib.IMyAidlCallBackInterface;
import com.helang.lib.IMyAidlInterface;
import com.zaozhuang.robot.utils.FaceDetectorManager;
import com.zaozhuang.robot.view.OffsetBackgroundSpan;
import com.zaozhuang.robot.websocket.ServiceUtils;
import com.zaozhuang.robot.websocket.SocketJobListEntity;
import com.zaozhuang.robot.websocket.socketService;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Random;

public class WelcomeActivity extends AppCompatActivity implements socketService.MessageListener {
    private static final int CAMERA_PERMISSION_REQUEST = 100;
    private IMyAidlInterface iMyAidlInterface;
    private ServiceCallBack serviceCallBack;
    private MyServiceConnection myServiceConnection;

    private final Handler handler = new Handler(Looper.getMainLooper());
    private TextView tvTime, tvDate;
    private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm", Locale.getDefault());
    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

    private int mTalkingState = 0;

    private static final int IDLE = 0;//闲置中，人和机器人都没说话
    private static final int MEN_TALKING = 1;//人在说话中
    private static final int ROBOT_THINKING = 2;//机器人请求大模型中
    private static final int ROBOT_ANSWERING = 3;//机器人回答中

    private TextView qaText, guideText, introText, remoteText;
    private boolean isForeground = false;
    private boolean isWaked = false;
    ArrayList<String> targetPinyins = new ArrayList<>();
    ArrayList<String> tips = new ArrayList<>();
    private socketService.LocalBinder mServiceBinder;
    private boolean mBound = false;
    String uuid = "";
    View listContainer;

    private ImageView leftIcon;
    private TextView centerText;
    private SharedPreferences sharedPreferences;

    private String welcomeStr = "";
    private App app;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mServiceBinder = (socketService.LocalBinder) service;
            socketService socketServiceInstance = mServiceBinder.getService();
            mBound = true;
            socketServiceInstance.setMessageListener(WelcomeActivity.this); // 注册监听
            // 发送消息示例
//            if (socketServiceInstance != null) {
//                socketServiceInstance.sendMessage("测试消息");
//            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
            mServiceBinder = null;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        setContentView(R.layout.activity_welcome);
        sharedPreferences = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        bindService();
        initView();
        initData();
//        startFaceDetection();
        initWebSocket();
        app = (App) getApplication();
    }

    private static final String HOST = "120.220.83.9:8333";

    private void initWebSocket() {
        String url = "ws://" + HOST + "/agent/chat/";
//        Log.e("TalkActivity uuid initWebSocket", uuid);
        String token = "";
        ServiceUtils.startWebSocketService(this, token, url);

        // 绑定服务
        bindWebSocketService();
    }

    private void bindWebSocketService() {
        Intent intent = new Intent(this, socketService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private void unbindWebSocketService() {
        if (mBound) {
            unbindService(mServiceConnection);
            mBound = false;
            mServiceBinder = null;
        }
    }

    private static final int GRID_SIZE = 3; // 3x3网格
    private RelativeLayout container;
    private int cellWidth, cellHeight;
    private int containerWidth;
    FaceDetectorManager faceDetectorManager;
    private TextView logText;

    private void initData() {
//        targetPinyins.add("xiaozao");
//        targetPinyins.add("xiaocao");
//        targetPinyins.add("xiaodao");
//        targetPinyins.add("xiaozhao");
//        targetPinyins.add("shexiaobao");
//        targetPinyins.add("sexiaobao");
//        targetPinyins.add("shenxiaobao");
//        targetPinyins.add("shengxiaobao");
//        targetPinyins.add("shuaixiaobao");
        targetPinyins.add("xiaobao");
//        tips.add("小枣小枣");
        tips.add("你吃饭了吗");
        tips.add("我要找工作");
        tips.add("你好");
        tips.add("你能干什么");
        tips.add("今天天气怎么样");
        tips.add("我要求职");
        tips.add("公积金怎么提取");
//        tips.add("有哪些职业培训补贴政策");
//        tips.add("失业青年就业见习补贴政策有哪些");
//        tips.add("毕业生就业创业补贴政策有哪些");
//        tips.add("残疾人就业基地有哪些奖励");
//        tips.add("人社局可以为老百姓提供哪些服务");
        tips.add("社保卡办理需要多长时间");
        tips.add("社保卡怎么激活");
        tips.add("社保卡密码怎么修改");
        tips.add("怎么查询社保卡账户余额");
        tips.add("养老保险可以自己缴纳吗");
        tips.add("如何查询养老保险缴费情况");
        tips.add("发生工伤怎么办");
        tips.add("社保卡的功能");
        tips.add("未成年人如何申领社保卡");
        tips.add("我想找份工作");
        tips.add("我想找份客服岗的工作");
        tips.add("给我推荐一份薛城区的工作");
        Collections.shuffle(tips);
    }

    private void startFaceDetection() {
        FaceDetectorManager.OnFaceDetectedListener listener = new FaceDetectorManager.OnFaceDetectedListener() {
            @Override
            public void onFaceDetected(int faceCount) {
//                Toast.makeText(WelcomeActivity.this, "人脸识别成功！", Toast.LENGTH_SHORT).show();
                startTTs("人脸识别成功,欢迎欢迎，热烈欢迎");
            }
        };
        faceDetectorManager = new FaceDetectorManager(this, listener);
        // 请求摄像头权限
        if (checkSelfPermission(android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED) {
            faceDetectorManager.startCamera();
        } else {
            requestPermissions(new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST);
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_PERMISSION_REQUEST && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            faceDetectorManager.startCamera();
        }
    }

    private void startTTs(String str) {
//        语音合成，机器人说话
//        startTTs
        if (!isForeground) {
            return;
        }
        if (iMyAidlInterface != null) {
            try {
                iMyAidlInterface.sendMessage("starttts", str);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void stopTTs() {
//        语音合成中断
//        stopTTs
        if (iMyAidlInterface != null) {
            try {
                iMyAidlInterface.sendMessage("stoptts", "");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private int clickCounter = 0;
    private long lastClickTime = 0;
    private void initView() {
        tvTime = findViewById(R.id.tv_time);
        tvDate = findViewById(R.id.tv_date);
        qaText = findViewById(R.id.qa_tv);
        guideText = findViewById(R.id.guide_tv);
        introText = findViewById(R.id.intro_tv);
        remoteText = findViewById(R.id.remote_tv);
        logText = (TextView) findViewById(R.id.logs);
        logText.setMovementMethod(ScrollingMovementMethod.getInstance());
        listContainer = findViewById(R.id.list_container);
        listContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (app.useDeviceWakeup) {
                    wakeUp();
                } else {
                    jumpTalkActivity();
                }
            }
        });
        leftIcon = findViewById(R.id.iv_icon);
        leftIcon.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // 获取当前点击时间
                long currentTime = System.currentTimeMillis();

                // 如果两次点击间隔超过1秒，重置计数器
                if (currentTime - lastClickTime > 1000) {
                    clickCounter = 1;
                } else {
                    clickCounter++;
                }
                lastClickTime = currentTime;

                // 当连续点击达到5次时触发
                if (clickCounter >= 5) {
                    // 执行原跳转逻辑
                    Intent intent = new Intent(WelcomeActivity.this, SettingsActivity.class);
                    startActivity(intent);
                    // 重置计数器
                    clickCounter = 0;
                }
            }
        });
        centerText = findViewById(R.id.center_wake_tv);
        App app = (App) getApplication();
        logText.setVisibility(app.isDebugMode ? View.VISIBLE : View.GONE);
        addOffSetBgForText();
        initFlowAnim();
        updateTime();
        startRealtimeUpdates();
    }

    private void startRecord() {
        if (iMyAidlInterface != null) {
            try {
                iMyAidlInterface.sendMessage("startrecord", "");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void wakeUp() {
        if (iMyAidlInterface != null) {
            try {
                /**
                 *  direct 为波束方位 以4麦阵列为例，取值0,1,2, 0为麦克风的第一与第二麦头之间波速,1为中间波速，2为三和四麦头的波速
                 */
                String direct = "1";
                iMyAidlInterface.sendMessage("wakeup", direct);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void stopRecord() {
        if (iMyAidlInterface != null) {
            try {
                iMyAidlInterface.sendMessage("stoprecord", "");
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    private void initFlowAnim() {
        container = findViewById(R.id.container);
        container.post(() -> {
            // 获取容器实际尺寸
            int totalWidth = container.getWidth();
            int totalHeight = container.getHeight();

            // 计算单元格尺寸
            cellWidth = totalWidth / GRID_SIZE;
            cellHeight = totalHeight / GRID_SIZE;

            // 生成随机数量（4-7）
            int z = new Random().nextInt(3) + 4;

            // 生成布局
            container.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    // 获取容器实际宽度
                    containerWidth = container.getWidth();
                    createViews(z);
                    startAnimation();
                    container.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }

            });
        });
    }

    private void createViews(int count) {
        // 生成不重复的随机位置
        List<Integer> positions = new ArrayList<>();
        for (int i = 0; i < GRID_SIZE * GRID_SIZE; i++) {
            positions.add(i);
        }
        Collections.shuffle(positions);

        // 创建指定数量的视图
        for (int i = 0; i < count; i++) {
            int pos = positions.get(i);
            addViewToCell(pos, i);
        }
    }

    private void addViewToCell(int cellPosition, int i) {
        // 计算单元格坐标
        int row = cellPosition / GRID_SIZE;
        int col = cellPosition % GRID_SIZE;

        // 创建新视图
        TextView tv = new TextView(this);
        tv.setText(tips.get(i));
        tv.setTextSize(24);
        tv.setPadding(16, 16, 16, 16);
        // 创建圆角透明背景
        GradientDrawable bgShape = new GradientDrawable();
        bgShape.setShape(GradientDrawable.RECTANGLE);
        bgShape.setCornerRadius(36);  // 8dp圆角
        bgShape.setOrientation(GradientDrawable.Orientation.TOP_BOTTOM);
        bgShape.setColors(new int[]{
                Color.parseColor("#5AB4FF"),
                Color.parseColor("#1E99FF")
        });
        // 可选添加白色边框
        bgShape.setStroke(1, Color.WHITE);
        tv.setBackground(bgShape);
        tv.setTextColor(Color.WHITE);
        tv.setGravity(Gravity.CENTER);

        // 设置布局参数
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT
        );
        // 测量视图实际尺寸
        tv.measure(View.MeasureSpec.makeMeasureSpec(cellWidth, View.MeasureSpec.AT_MOST),
                View.MeasureSpec.makeMeasureSpec(cellHeight, View.MeasureSpec.AT_MOST));
        int viewWidth = tv.getMeasuredWidth();
        int viewHeight = tv.getMeasuredHeight();
        // 计算最大可偏移范围（考虑安全边距）
        int maxHorizontalOffset = cellWidth - viewWidth - dpToPx(4); // 左右各留2dp边距
        int maxVerticalOffset = cellHeight - viewHeight - dpToPx(4); // 上下各留2dp边距

        // 生成随机位置
        Random random = new Random();
        int leftMargin = col * cellWidth + dpToPx(2) +
                (maxHorizontalOffset > 0 ? random.nextInt(maxHorizontalOffset) : 0);
        int topMargin = row * cellHeight + dpToPx(2) +
                (maxVerticalOffset > 0 ? random.nextInt(maxVerticalOffset) : 0);
        params.leftMargin = Math.max(0, leftMargin);
        params.topMargin = Math.max(0, topMargin);

//        params.leftMargin = col * cellWidth;
//        params.topMargin = row * cellHeight;

        container.addView(tv, params);
        startAnimation();
    }

    private void startAnimation() {
        ValueAnimator animator = ValueAnimator.ofFloat(0f, 1f);
        animator.setRepeatCount(ValueAnimator.INFINITE);
        animator.setDuration(15000); // 总动画时长
        animator.setInterpolator(new LinearInterpolator());

        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                long currentTime = System.currentTimeMillis();

                for (int i = 0; i < container.getChildCount(); i++) {
                    View child = container.getChildAt(i);
                    float speed = 0.4f; // 控制移动速度

                    // 计算新的X位置
                    float newX = child.getX() - speed;

                    // 循环检测
                    if (newX + containerWidth / GRID_SIZE < 0) {
                        newX = containerWidth;
                    }

                    child.setX(newX);
                }
            }
        });
        animator.start();
    }

    private int dpToPx(int dp) {
        return (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }

    private void addOffSetBgForText() {
        // 计算偏移量（示例：偏移半个字符宽度/高度）
        float textSize = qaText.getTextSize(); // 获取当前文本大小
        float offsetX = 0;  // 向右偏移
        float offsetY = (float) (textSize * 0.7);  // 向下偏移
        OffsetBackgroundSpan span = new OffsetBackgroundSpan(
                Color.parseColor("#006AFF"),
                offsetX,
                offsetY,
                textSize
        );
        //得加点空格，要不最后一行下面没有行间距，导致偏移的部分被crop了
        SpannableStringBuilder spannableText = new SpannableStringBuilder("完备的政策文件库，强大的搜索匹配能力\n语音对话，问你所想，打造交互新模式\n大模型智能问答，精准政策解析回复\n                  ");
        String target = "完备的政策文件库，强大的搜索匹配能力\n语音对话，问你所想，打造交互新模式\n大模型智能问答，精准政策解析回复";
        spannableText.setSpan(
                span,
                0,   // 起始位置
                target.length(),   // 结束位置（不包含）
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        );
        qaText.setText(spannableText);
        span = new OffsetBackgroundSpan(
                Color.parseColor("#7B59FF"),
                offsetX,
                offsetY,
                textSize
        );
        spannableText = new SpannableStringBuilder("无匹配岗位？试试一键求职发布\n主动展示求职意向，让好工作主动来找你！\n                  ");
        target = "无匹配岗位？试试一键求职发布\n主动展示求职意向，让好工作主动来找你！\n";
        spannableText.setSpan(
                span,
                0,   // 起始位置
                target.length(),   // 结束位置（不包含）
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        );
        span = new OffsetBackgroundSpan(
                Color.parseColor("#00B170"),
                offsetX,
                offsetY,
                textSize
        );
        guideText.setText(spannableText);
        spannableText = new SpannableStringBuilder("海量职位库：对接枣工快递，连接数千家企业招聘需求\n智能匹配推送：系统根据个人要求推荐高契合岗位\n高效沟通：支持在线视频面试，在线简历投递，一键直达\n                  ");
        target = "海量职位库：对接枣工快递，连接数千家企业招聘需求\n智能匹配推送：系统根据个人要求推荐高契合岗位\n高效沟通：支持在线视频面试，在线简历投递，一键直达\n";
        spannableText.setSpan(
                span,
                0,   // 起始位置
                target.length(),   // 结束位置（不包含）
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        );
        span = new OffsetBackgroundSpan(
                Color.parseColor("#FF7813"),
                offsetX,
                offsetY,
                textSize
        );
        introText.setText(spannableText);
        spannableText = new SpannableStringBuilder("在线面试\n智能、高效、快捷、直聘\n                  ");
        target = "在线面试\n";
        spannableText.setSpan(
                span,
                0,   // 起始位置
                target.length(),   // 结束位置（不包含）
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
        );
        remoteText.setText(spannableText);
    }


    @Override
    protected void onStop() {
        super.onStop();
        isForeground = false;

    }

    @Override
    protected void onResume() {
        super.onResume();
        isForeground = true;
        if (app.useDeviceWakeup) {

        } else {
            wakeUp();
        }
        handler.post(new Runnable() {
            @Override
            public void run() {
                if(mServiceBinder != null){
                    socketService socketServiceInstance = mServiceBinder.getService();
                    socketServiceInstance.setMessageListener(WelcomeActivity.this);
                }
            }
        });
        String savedWakeWord = sharedPreferences.getString(KEY_WAKE_WORD, wake_default);
        String totalStr = "对我说“" + savedWakeWord + "”\n开启智慧新体验";
        centerText.setText(totalStr);
        welcomeStr = sharedPreferences.getString(KEY_WELCOME_MSG, welcome_default);
//        if(isWaked){
//            startRecord();
//        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService();
        handler.removeCallbacksAndMessages(null); // 防止内存泄漏
        unbindWebSocketService();
    }

    // 更新时间显示
    private void updateTime() {
        Date now = new Date();
        tvTime.setText(timeFormat.format(now));
        tvDate.setText(dateFormat.format(now));
    }


    // 启动定时更新
    private void startRealtimeUpdates() {
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                updateTime();
                handler.postDelayed(this, 1000); // 每1秒更新一次
            }
        }, 1000);
    }

    private void bindService() {
        myServiceConnection = new MyServiceConnection();
        serviceCallBack = new ServiceCallBack();
        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.aobo.robot.ai3",
                "com.aobo.aibot.aidl.MyService"));
        startService(intent);
        bindService(intent, myServiceConnection, BIND_AUTO_CREATE);
    }

    private void unbindService() {
        if (myServiceConnection != null) {
            try {
                if (iMyAidlInterface != null) {
                    iMyAidlInterface.unregisterListener(serviceCallBack);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            unbindService(myServiceConnection);
        }
    }

    @Override
    public void onMessageStart(String conversationId) {

    }

    @Override
    public void onMessageTypeChanged(String type) {

    }

    @Override
    public void onMessageReceived(Object socketEntity) {

    }

    @Override
    public void onCommandReceived(String answer) {
        Log.e("potter", "onCommandReceived:" + answer);
        if (isForeground) {
            if (answer.equals("welcome")) {
//                startTTs("各位领导：欢迎莅临“枣工快道”就业服务综合体指导！“榴住人才，职达未来”我是您的向导“社小保”。");
                startTTs(welcomeStr);
            }
        }
    }

    @Override
    public void onJobListMessage(String introMsg, List<SocketJobListEntity> jobList) {

    }

    class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            iMyAidlInterface = IMyAidlInterface.Stub.asInterface(iBinder);

            handler.post(new Runnable() {
                @Override
                public void run() {
                    //注册回调
                    if (iMyAidlInterface != null) {
                        try {
                            iMyAidlInterface.registerListener(serviceCallBack);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    //服务绑定后就开始语音录入
                    if (app.useDeviceWakeup) {

                    } else {
                        wakeUp();
                    }
//                    startRecord();
                }
            });
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    }

    private String convertToPinyin(String chinese) {
        Transliterator transliterator = null;
        Transliterator transliterator2 = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            //转的是带音调的
            transliterator = Transliterator.getInstance("Han-Latin");
            //干掉音调
            transliterator2 = Transliterator.getInstance("Latin-ASCII");
            String str = transliterator.transliterate(chinese);
            return transliterator2.transliterate(str).replaceAll("\\s+", "");
        }
        return "";
    }

    /**
     * service回调client的类
     * tag
     * 为1是返回识别音量
     * 为2是返回识别的内容
     * 为3是合成消息
     * 为4是唤醒消息
     * 为front_ultrasound 是前超声波消息
     * 为back_ultrasound 为后超声波消息
     * 为ultrasound_distance 为超声波距离
     */
    class ServiceCallBack extends IMyAidlCallBackInterface.Stub {

        @Override
        public void callback(final String tag, final String message) throws RemoteException {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String pingyin = convertToPinyin(message);
                    if (!tag.equals("1") && logText != null) {
                        logText.append("tag = " + tag + "  message=" + message + "  pingyin=" + pingyin + "\n");
                    }
                    if (!isForeground) {
                        return;
                    }
                    if (tag.equals("4")) {
                        if (message.startsWith("wake up")) {
                            isWaked = true;
                            if (app.useDeviceWakeup) {
                                jumpTalkActivity();
                                return;
                            } else {
                                startRecord();
                            }
                        }
                    }
                    if (app.useDeviceWakeup) {
                        return;
                    }
                    //语音播报结束或中断-->开启录制新的一轮人的说话，语音识别
                    if (tag.equals("3") && (message.equals("ttsover") || message.equals("ttsstop"))) {
                        startRecord();
                    }
                    if (tag.equals("2")) {
                        Log.e("Welcome record message", message);
                        if (message.equals("stoprecord")) {
                            //此时的情景是人没有说话，我们继续startRecord;
                            startRecord();
                            return;
                        }
//                        if (message.contains("小枣")) {
                        for (int i = 0; i < targetPinyins.size(); i++) {
                            String targetPinyin = targetPinyins.get(i);
                            if (pingyin.contains(targetPinyin)) {
//                                unbindService();
                                jumpTalkActivity();
                                break;
                            }
                        }
                    }
                }
            });
        }
    }

    private void jumpTalkActivity() {
//        stopTTs();
        Intent intent = new Intent(WelcomeActivity.this, TalkActivity.class);
        startActivity(intent);
    }
}